package progress;


import java.util.concurrent.locks.ReentrantLock;

/**
 * 模拟抢票实现 使用ReentranLock 实现公平锁机制,默认为falase 不公平
 */
public class TickPiaolock implements Runnable {
    int count = 10;
    //记录第几张票
    int countRecord = 0;
    boolean flag = true;
    private ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (flag) {
//            加锁
           lock.lock();
            if (count <= 0) {
                flag = false;
                return;
            }
            count--;
            countRecord++;
            System.out.println("当线线程：" + Thread.currentThread().getName() + "\t抢到第几张票：" + countRecord + "\t剩余票数：" + count);
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
//                释放锁
                lock.unlock();
            }
        }

    }
}



